package com.iflytek.jzcpx.procuracy.common.util;

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;

/**
 * 通过java获取图片的宽和高
 */
public class ImageUtil {
    private static Logger logger= LoggerFactory.getLogger(ImageUtil.class);
    /**
     * 获取图片宽度
     * @param file  图片文件
     * @return 宽度
     */
    public static int getImgWidth(File file) {
        int ret = -1;
        try(InputStream is = new FileInputStream(file)) {
            BufferedImage src = ImageIO.read(is);
            ret = src.getWidth(null); // 得到源图宽
        } catch (Exception e) {
            logger.warn("getImgWidth {},{}",e,e.getMessage());
        }
        return ret;
    }

    /**
     *
     * @param bytes
     * @return
     */
    public static File getFileFromBytes(byte[] bytes)
    {
        File file = new File(UUID.randomUUID().toString());
        FileInputStream fileInputStream = null;
        try {
            OutputStream output = new FileOutputStream(file);
            BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
            bufferedOutput.write(bytes);
            bufferedOutput.flush();
            bufferedOutput.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  file;
    }


    /**
     * 获取图片高度
     * @param file  图片文件
     * @return 高度
     */
    public static int getImgHeight(File file) {
        int ret = -1;
        try(InputStream is = new FileInputStream(file)) {
            BufferedImage src = ImageIO.read(is);
            ret = src.getHeight(null); // 得到源图高
        } catch (Exception e) {
           logger.warn("getImgHeight {},{}",e,e.getMessage());
        }
        return ret;
    }

    /**
     * 图片文件格式转换
     *
     * @param imageBytes 源图片对应的
     * @param imageExt   转换图片格式
     * @param dest       目标文件地址
     */
    public static void convert(byte[] imageBytes,String imageExt,String dest,double scale) {
//        try(InputStream is = new ByteArrayInputStream(imageBytes)) {
//            BufferedImage src = ImageIO.read(is);
//            // create a blank, RGB, same width and height, and a white background
//            BufferedImage newBufferedImage = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_RGB);
//            newBufferedImage.createGraphics().drawImage(src, 0, 0, Color.WHITE, null);
//            File fo = new File(dest);
//            ImageIO.write(newBufferedImage, imageExt, fo);
//        } catch (Exception e) {
//           logger.warn("getImgWidth {},{}",e,e.getMessage());
//        }
        try {
            //Thumbnails.of(new ByteArrayInputStream(imageBytes)).scale(scale).outputFormat(imageExt).toFile(dest);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     *
     * @param imageBytes
     * @param imageExt
     * @param scale
     * @return
     */
    public static byte[] reduceImgByRate(byte[] imageBytes,String imageExt,double scale) {
//        try(InputStream is = new ByteArrayInputStream(imageBytes)) {
//            BufferedImage src = ImageIO.read(is);
//            // create a blank, RGB, same width and height, and a white background
//            BufferedImage newBufferedImage = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_RGB);
//            newBufferedImage.createGraphics().drawImage(src, 0, 0, Color.WHITE, null);
//            File fo = new File(dest);
//            ImageIO.write(newBufferedImage, imageExt, fo);
//        } catch (Exception e) {
//           logger.warn("getImgWidth {},{}",e,e.getMessage());
//        }
        try {
            ByteArrayOutputStream byteOutputStream=new ByteArrayOutputStream();
            Thumbnails.of(new ByteArrayInputStream(imageBytes)).scale(scale).outputFormat(imageExt).toOutputStream(byteOutputStream);
            return byteOutputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * <p>Title: cutImage</p>
     * <p>Description:  根据原图与裁切size截取局部图片</p>
     *
     * @param buf    源图片
     * @param output 图片输出流
     * @param rect   需要截取部分的坐标和大小
     * @param suffix ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
     */
    public static void cutImage(byte[] buf, OutputStream output, Rectangle rect, String suffix) {

        InputStream fis = new ByteArrayInputStream(buf);
        ImageInputStream iis = null;
        try {
            // 将FileInputStream 转换为ImageInputStream
            iis = ImageIO.createImageInputStream(fis);
            // 根据图片类型获取该种类型的ImageReader
            ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next();
            reader.setInput(iis, true);
            ImageReadParam param = reader.getDefaultReadParam();
            param.setSourceRegion(rect);
            BufferedImage bi = reader.read(0, param);
            ImageIO.write(bi, suffix, output);
        } catch (Exception ignored) {
        } finally {
            try {
                fis.close();
                if (iis != null) iis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 旋转
     *
     * @param degree 旋转角度
     * @throws Exception
     */
    public static byte[] spin(int degree, byte[] imageByte) throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        //Thumbnails.of(new ByteArrayInputStream(imageByte)).rotate(degree).scale(1).outputQuality(1).toOutputStream(os);
        return os.toByteArray();
    }
}
